/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */
package cc.iotkit.manager.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.Request;
import cc.iotkit.common.constant.Constants;
import cc.iotkit.common.thing.ThingModelMessage;
import cc.iotkit.common.thing.ThingService;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.manager.IAlertConfigData;
import cc.iotkit.data.manager.IAlertRecordData;
import cc.iotkit.data.manager.IDeviceInfoData;
import cc.iotkit.data.manager.IThingModelData;
import cc.iotkit.message.model.Message;
import cc.iotkit.model.alert.AlertConfig;
import cc.iotkit.model.alert.AlertRecord;
import cc.iotkit.model.device.DeviceInfo;
import cc.iotkit.model.product.ThingModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AlertService {

    @Autowired
    private IAlertConfigData alertConfigData;
    @Autowired
    private IAlertRecordData alertRecordData;
    @Autowired
    private IDeviceInfoData deviceInfoData;
    @Autowired
    @Qualifier("thingModelDataCache")
    private IThingModelData thingModelData;

    public AlertConfig createAlertConfig(AlertConfig alertConfig) {
        return alertConfigData.save(alertConfig);
    }

    public AlertConfig updateAlertConfig(AlertConfig alertConfig) {
        return alertConfigData.save(alertConfig);
    }

    public void deleteAlertConfigById(Long id) {
        alertConfigData.deleteById(id);
    }

    public Paging<AlertConfig> selectAlertConfigPage(PageRequest<AlertConfig> request) {
        return alertConfigData.selectAlertConfigPage(request);
    }

    public Paging<AlertRecord> selectAlertRecordPage(PageRequest<AlertRecord> request) {
        return alertRecordData.selectAlertConfigPage(request);
    }

    public List<AlertRecord> selectAlertRecord(AlertRecord query) {
        List<AlertRecord> results = alertRecordData.selectAlertRecord(query);
        return results;
    }

    /***
     * 生成告警记录
     * @param config
     * @param message
     */
    public void addAlert(AlertConfig config, Message message) {
        log.info("正在添加告警消息：",message.getContent());
        ThingModelMessage msg= message.getMessage();
        ThingModel thingModel = thingModelData.findByProductKey(msg.getProductKey());

        DeviceInfo deviceInfo= deviceInfoData.findByDeviceId(message.getMessage().getDeviceId());
        Map<String,String> params=new HashMap<>();
        params.put(Constants.ALTER_MESSAGE_TITLE,deviceInfo.getDeviceName());
        /*
        添加参数，根据上传的参数与物模型参数匹配并替换模板变量
        1.如果是枚举类型，在输出脚本中定义的变量必须与模型中的变量名称一至，才能正确输出枚举value值，枚举不到时直接输出key值
        */
        message.getParam().forEach((k, v)->{
            String value="";
            if(msg.getType().equals("event")) {
                List<ThingModel.Event> events = thingModel.getModel().getEvents();
                for(ThingModel.Event event : events) {
                    if(event.getIdentifier().equals(msg.getIdentifier())){
                        List<ThingModel.Parameter> parameters= event.getOutputData();
                        for(ThingModel.Parameter parameter:parameters){
                            if(parameter.getIdentifier().equals(k)){
                                ThingModel.DataType dataType=  parameter.getDataType();
                                switch (dataType.getType()) {
                                    case "enum":
                                        LinkedHashMap spec=(LinkedHashMap)dataType.getSpecs();
                                        if(spec.get(v.toString())!=null)
                                            value= spec.get(v.toString()).toString();
                                        break;
                                    default:
                                        break;
                                }
                                break;
                            }
                        }
                        break;
                    }
                };
            }
            else if(msg.getType().equals("property")){
                List<ThingModel.Property> properties=thingModel.getModel().getProperties();
                for(ThingModel.Property property:properties){
                    if(property.getIdentifier().equals(k)){
                        ThingModel.DataType dataType= property.getDataType();
                        switch (dataType.getType()) {
                            case "enum":
                                LinkedHashMap spec=(LinkedHashMap)dataType.getSpecs();
                                if(spec.get(v.toString())!=null)
                                    value= spec.get(v.toString()).toString();
                                break;
                            default:
                                break;
                        }
                        //params.put(k,value);
                        break;
                    }
                }
            }
            params.put(k,value==""?v.toString():value);
            //params.put(k,v.toString());
        });
        String  content=StringUtils.formatReplaceVars(message.getContent(),params);
        alertRecordData.save(AlertRecord.builder()
                .level(config.getLevel())
                .tenantId(deviceInfo.getTenantId())
                .createDept(deviceInfo.getCreateDept())
                .name(config.getName())
                .readFlg(false)
                .uid(deviceInfo.getUid())
                .alertTime(System.currentTimeMillis())
                .details(content)
                .deviceId(deviceInfo.getDeviceId())
                .build());
    }
}
